import { Button, Table, Modal, message } from 'antd'
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import base from '../../routes/baseUrl'
import { CompassOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router'

const { confirm } = Modal

export default function TeacherList() {

  const [teacherList, setTeacherList] = useState([])
  const { id, changePassword } = JSON.parse(sessionStorage.getItem('token'))
  const navigate = useNavigate()

  useEffect(() => {
    axios.get(base + '/teachers?_embed=students').then(res => {
      setTeacherList(res.data)
    })
  }, [])

  const columns = [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}` // 序号自增
    },
    {
      title: '工号',
      dataIndex: 'id'
    },
    {
      title: '教师姓名',
      dataIndex: 'name'
    },
    {
      title: '操作',
      render: (item) => <Button disabled={item.students.length > 2 ? true : false} onClick={() => confirmSelect(item)}>选择</Button>
    }
  ]

  const confirmSelect = (item) => {
    confirm({
      title: `确定要选择${item.name}老师吗？`,
      icon: <CompassOutlined spin={true} />,
      content: '如需退选，请转至“我的导师”页面',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        axios.patch(base + `/students/${id}`, {
          teacherId: item.id
        }).then(res => {
          sessionStorage.setItem('token', JSON.stringify({...res.data, changePassword}))
          message.success('选择成功')
          navigate('/selected')
        }).catch(reason => {
          message.error('发生错误，请重试')
          console.log(reason)
        })
      },
      onCancel() {
        console.log('操作取消')
      }
    })
  }

  return (
    <Table
      columns={columns}
      dataSource={teacherList}
      title={() => <h2>导师列表</h2>}
      pagination={{ pageSize: 5 }}
      rowKey='id'
    />
  )
}
